package org.dync.giftlibrary;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.ComponentTransition;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.utils.LayoutAlignment;
import ohos.app.Context;
import org.dync.giftlibrary.util.HeLog;
import org.dync.giftlibrary.widget.GiftFrameLayout;
import org.dync.giftlibrary.widget.GiftModel;
import org.dync.giftlibrary.widget.ICustormAnim;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by KathLine on 2017/1/8.
 */

public class GiftControl implements GiftFrameLayout.LeftGiftAnimationStatusListener {
    private static final String TAG = "GiftControl";
    protected Context mContext;
    /**
     * 自定义动画
     */
    private ICustormAnim custormAnim;
    /**
     * 是否开启隐藏动画
     */
    private boolean isHideMode;
    /**
     * 当前所有礼物动画布局的显示方式
     */
    private int curDisplayMode = FROM_BOTTOM_TO_TOP;
    public static final int FROM_BOTTOM_TO_TOP = 0;//由下往上
    public static final int FROM_TOP_TO_BOTTOM = 1;//由上往下
    /**
     * 礼物队列
     */
    private ArrayList<GiftModel> mGiftQueue;

    /**
     * 添加礼物布局的父容器
     */
    private DirectionalLayout mGiftLayoutParent;
    /**
     * 最大礼物布局数
     */
    private int mGiftLayoutMaxNums;

    public GiftControl(Context context) {
        mContext = context;
        mGiftQueue = new ArrayList<>();
    }

    public GiftControl setCustormAnim(ICustormAnim anim) {
        custormAnim = anim;

        return this;
    }

    /**
     * @param giftLayoutParent 存放礼物控件的父容器
     * @param giftLayoutNums 礼物控件的数量
     * @return GiftControl
     */
    public  synchronized GiftControl setGiftLayout(DirectionalLayout giftLayoutParent, int giftLayoutNums) {
        if (giftLayoutNums <= 0) {
            throw new IllegalArgumentException("GiftFrameLayout数量必须大于0");
        }
        if (giftLayoutParent.getChildCount() > 0) {//如果父容器没有子孩子，就进行添加
            return this;
        }
        mGiftLayoutParent = giftLayoutParent;
        mGiftLayoutMaxNums = giftLayoutNums;
        ComponentTransition transition = new ComponentTransition();
        transition.setAnimatorProperty(ComponentTransition.SELF_SHOW, transition.getAnimatorProperty(ComponentTransition.SELF_SHOW));
        transition.setAnimatorProperty(ComponentTransition.SELF_GONE, transition.getAnimatorProperty(ComponentTransition.SELF_GONE));
        transition.setAnimatorProperty(ComponentTransition.OTHERS_SHOW, transition.getAnimatorProperty(ComponentTransition.OTHERS_SHOW));
        transition.setAnimatorProperty(ComponentTransition.OTHERS_GONE, transition.getAnimatorProperty(ComponentTransition.OTHERS_GONE));
        transition.setAnimatorProperty(ComponentTransition.CHANGING, transition.getAnimatorProperty(ComponentTransition.CHANGING));
        mGiftLayoutParent.setComponentTransition(transition);

        return this;
    }

    /**
     * 是否开启隐藏动画
     *
     * @param isHideMode
     * @return GiftControl
     */
    public synchronized GiftControl setHideMode(boolean isHideMode) {
        this.isHideMode = isHideMode;
        return this;
    }

    /**
     * 当前所有礼物动画布局的显示方式
     *
     * @param displayMode {@link #FROM_BOTTOM_TO_TOP}、{@link #FROM_TOP_TO_BOTTOM}
     * @return GiftControl
     */
    public  synchronized GiftControl setDisplayMode(int displayMode) {
        this.curDisplayMode = displayMode;
        return this;
    }

    public void loadGift(GiftModel gift) {
        loadGift(gift, true);
    }

    /**
     * 加入礼物，具有实时连击效果
     *
     * @param gift
     * @param supportCombo 是否支持实时连击，如果为true：支持，否则不支持
     */
    public synchronized void loadGift(GiftModel gift, boolean supportCombo) {
        if (mGiftQueue != null) {
            if (supportCombo) {
                GiftFrameLayout giftFrameLayout;
                for (int i = 0; i < mGiftLayoutParent.getChildCount(); i++) {
                    giftFrameLayout = (GiftFrameLayout) mGiftLayoutParent.getComponentAt(i);
                    if (giftFrameLayout.isShowing()) {
                        if (giftFrameLayout.getCurrentGiftId().equals(gift.getGiftId()) && giftFrameLayout.getCurrentSendUserId().equals(gift.getSendUserId())) {
                            //连击
                            HeLog.d(TAG, "addGiftQueue: ========giftFrameLayout(" + giftFrameLayout.getIndex() + ")连击========礼物：" + gift.getGiftId() + ",连击X" + gift.getGiftCount());
                            if (gift.getJumpCombo() > 0) {
                                //触发连击，这里不要在加上giftCount了git，因为你要连击的数已经变成jumpCombo了
                                giftFrameLayout.setGiftCount(gift.getJumpCombo());
                            } else {
                                giftFrameLayout.setGiftCount(gift.getGiftCount());
                            }
                            giftFrameLayout.setSendGiftTime(gift.getSendGiftTime());
                            return;
                        }
                    }
                }
            }

            addGiftQueue(gift, supportCombo);
        }
    }

    private void addGiftQueue(final GiftModel gift, final boolean supportCombo) {
        if (supportCombo) {
            for (GiftModel model : mGiftQueue) {
                if (model.getGiftId().equals(gift.getGiftId()) && model.getSendUserId().equals(gift.getSendUserId())) {
                    HeLog.d(TAG, "addGiftQueue: ========已有集合========" + gift.getGiftId() + ",礼物数：" + gift.getGiftCount());
                    model.setGiftCount(model.getGiftCount() + gift.getGiftCount());
                    return;
                }
            }
        }

        mGiftQueue.add(gift);
        showGift();
    }

    /**
     * 显示礼物
     */
    public synchronized void showGift() {
        if (isEmpty()) {
            return;
        }
        GiftFrameLayout giftFrameLayout;
        int childCount = mGiftLayoutParent.getChildCount();
        HeLog.d(TAG, "showGift: 礼物布局的个数" + childCount);
        if (childCount < mGiftLayoutMaxNums) {
            //没有超过最大的礼物布局数量，可以继续添加礼物布局
            giftFrameLayout = new GiftFrameLayout(mContext);
            giftFrameLayout.setIndex(0);
            giftFrameLayout.setGiftAnimationListener(this);
            giftFrameLayout.setHideMode(isHideMode);
            ComponentContainer.LayoutConfig layoutConfig = new ComponentContainer.LayoutConfig(
                    ComponentContainer.LayoutConfig.MATCH_PARENT
                    , ComponentContainer.LayoutConfig.MATCH_CONTENT);
            giftFrameLayout.setLayoutConfig(layoutConfig);

            //TODO 此处需要看结果调整
            if (curDisplayMode == FROM_TOP_TO_BOTTOM) {
                mGiftLayoutParent.addComponent(giftFrameLayout, 0);
                mGiftLayoutParent.setAlignment(LayoutAlignment.TOP);
            } else {
                mGiftLayoutParent.addComponent(giftFrameLayout);
                mGiftLayoutParent.setAlignment(LayoutAlignment.BOTTOM);
            }

            HeLog.d(TAG, "showGift: begin->集合个数：" + mGiftQueue.size());
            boolean hasGift = giftFrameLayout.setGift(getGift());
            if (hasGift) {
                giftFrameLayout.startAnimation(custormAnim);
            }
            HeLog.d(TAG, "showGift: end->集合个数：" + mGiftQueue.size());
        } else {
            //超过了进行等待
        }
    }

    /**
     * 取出礼物
     *
     * @return GiftModel
     */
    private synchronized GiftModel getGift() {
        GiftModel gift = null;
        if (mGiftQueue.size() != 0) {
            gift = mGiftQueue.get(0);
            mGiftQueue.remove(0);
            HeLog.d(TAG, "getGift---集合个数：" + mGiftQueue.size() + ",送出礼物---" + gift.getGiftId() + ",礼物数X" + gift.getGiftCount());
        }
        return gift;
    }


    /**
     * 获取正在展示礼物的个数（即GiftFragmeLayout展示的个数）
     *
     * @return int
     */
    public synchronized int getShowingGiftLayoutCount() {
        int count = 0;
        GiftFrameLayout giftFrameLayout;
        for (int i = 0; i < mGiftLayoutParent.getChildCount(); i++) {
            giftFrameLayout = (GiftFrameLayout) mGiftLayoutParent.getComponentAt(i);
            if (giftFrameLayout.isShowing()) {
                count++;
            }
        }
        return count;
    }

    @Override
    public void dismiss(GiftFrameLayout giftFrameLayout) {
        reStartAnimation(giftFrameLayout, giftFrameLayout.getIndex());
    }

    private void reStartAnimation(final GiftFrameLayout giftFrameLayout, final int index) {
        //动画结束，这时不能触发连击动画
        giftFrameLayout.setCurrentShowStatus(false);
        HeLog.d(TAG, "reStartAnimation: 动画结束");
        AnimatorProperty animatorSet = (AnimatorProperty) giftFrameLayout.endAnmation(custormAnim);
        if (animatorSet != null) {
            animatorSet.setStateChangedListener(new Animator.StateChangedListener() {
                @Override
                public void onStart(Animator animator) {

                }

                @Override
                public void onStop(Animator animator) {

                }

                @Override
                public void onCancel(Animator animator) {

                }

                @Override
                public void onEnd(Animator animator) {
                    HeLog.d(TAG, "礼物动画dismiss: index = " + index);
                    //动画完全结束
                    giftFrameLayout.CurrentEndStatus(true);
                    giftFrameLayout.setGiftViewEndVisibility(isEmpty());
                    mGiftLayoutParent.removeComponent(giftFrameLayout);
                    showGift();
                }

                @Override
                public void onPause(Animator animator) {

                }

                @Override
                public void onResume(Animator animator) {

                }
            });
        }
        animatorSet.start();
    }

    public GiftControl reSetGiftLayout(DirectionalLayout giftLayoutParent, int giftLayoutNums) {
        return setGiftLayout(giftLayoutParent, giftLayoutNums);
    }

    /**
     * 清除所有礼物
     */
    public synchronized void cleanAll() {
        if (mGiftQueue != null) {
            mGiftQueue.clear();
        }
        GiftFrameLayout giftFrameLayout;
        for (int i = 0; i < mGiftLayoutParent.getChildCount(); i++) {
            giftFrameLayout = (GiftFrameLayout) mGiftLayoutParent.getComponentAt(i);
            if (giftFrameLayout != null) {
                giftFrameLayout.clearHandler();
                giftFrameLayout.firstHideLayout();
            }
        }
        mGiftLayoutParent.removeAllComponents();
    }

    /**
     * 礼物是否为空
     *
     * @return boolean
     */
    public synchronized boolean isEmpty() {
        if (mGiftQueue == null || mGiftQueue.size() == 0) {
            return true;
        } else {
            return false;
        }
    }
}
